﻿using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Tagging;

namespace Behaviorize.TextEditor.Coloring
{
	internal sealed class ColorClassifier : ITagger<ClassificationTag>
	{
		readonly ITagAggregator<ColorTag> _aggregator;
		IDictionary<TokenType, IClassificationType> _classificationTypes;

		internal ColorClassifier(ITagAggregator<ColorTag> featureTagAggregator,
							   IClassificationTypeRegistryService typeService)
		{
			_aggregator = featureTagAggregator;
			_classificationTypes = new Dictionary<TokenType, IClassificationType>();
			_classificationTypes[TokenType.And] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Description] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Examples] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Feature] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Given] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Goal] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Motivation] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Role] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Scenario] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.Then] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.When] = typeService.GetClassificationType("keyword");
			_classificationTypes[TokenType.ExampleTablePipe] = typeService.GetClassificationType("examplepipe");
			_classificationTypes[TokenType.ExampleUsage] = typeService.GetClassificationType("exampleusage");
			_classificationTypes[TokenType.Erroneus] = typeService.GetClassificationType("erroneous");
		}

		public event EventHandler<SnapshotSpanEventArgs> TagsChanged
		{
			add { }
			remove { }
		}

		public IEnumerable<ITagSpan<ClassificationTag>> GetTags(NormalizedSnapshotSpanCollection spans)
		{
			foreach (var tagSpan in this._aggregator.GetTags(spans))
			{
				var tagSpans = tagSpan.Span.GetSpans(spans[0].Snapshot);
				yield return new TagSpan<ClassificationTag>(tagSpans[0], new ClassificationTag(_classificationTypes[tagSpan.Tag.Type]));
			}
		}
	}
}